import os

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from fastapi.templating import Jinja2Templates
from tortoise.exceptions import DoesNotExist

from app.models.models import *


class Response:
    @staticmethod
    def do(data, msg):
        return JSONResponse(content={"data": data, "msg": msg})


router = APIRouter()
template = Jinja2Templates(directory=os.path.dirname(os.path.abspath(__file__)))


@router.get("/products/admin")
def index(req: Request):
    # 把用户传递的username放入到魔板引擎中， 后端叫做username，前端叫做name
    return template.TemplateResponse("ProductsAdmin.html", context={"request": req})


@router.post("/products")  # 增加产品
async def add_product(product: ProductIn_Pydantic):
    obj = await Product_Pydantic.from_tortoise_orm(await Product.create(**product.dict(exclude_unset=True)))
    return Response.do(obj.dict(), "Success.New object returned.")


@router.delete("/products/{product_id}")  # 删除产品
async def delete_product(product_id: int):
    try:
        obj = await Product_Pydantic.from_queryset_single(Product.get(id=product_id))
    except DoesNotExist:
        return Response.do(None, "Failed.ID does not exist")

    product = await Product.filter(id=product_id).update(deleted=True)
    return Response.do(None, "Success.Soft deleted")


@router.put("/products/{product_id}")  # 更新产品
async def update_product(product_id: int, product: ProductIn_Pydantic):
    try:
        obj = await Product_Pydantic.from_queryset_single(Product.get(id=product_id))
    except DoesNotExist:
        return Response.do(None, "Failed.ID does not exist")
    except Exception as e:
        print("ovo", e, type(e))

    await Product.filter(id=product_id).update(**product.dict(exclude_unset=True))
    obj = await Product_Pydantic.from_tortoise_orm(await Product.get_or_none(id=product_id))
    return Response.do(obj.dict(), "Success.Updated object returned.")


@router.get("/products/all", tags=["Products"], summary="Get all products",
            description="Retrieve a list of all products")
async def get_all_products():
    objs = await Product_Pydantic.from_queryset(Product.all())
    return Response.do([obj.dict() for obj in objs], "Success.The object wanted returned.")


@router.get("/products/{product_id}")  # 查找单个产品
async def get_product(product_id: int):
    try:
        obj = await Product_Pydantic.from_queryset_single(Product.get(id=product_id))
        return Response.do(obj.dict(), "Success.The object wanted returned.")
    except DoesNotExist:
        return Response.do(None, "Failed.ID does not exist")
